import jwt from 'jsonwebtoken';
import {registerUser, loginUser}  from '../service/index.js';
import { PRIVATE_KEY } from  "../app/config.js";
import response from "../utils/response.js";
import NetCode from "../constants/NetCode.js";

// 注册
export async function register(ctx){
    const user = ctx.request.body
    try {
        const result = await registerUser(user)
        ctx.body = response(NetCode.SUCCESS, result, '注册成功');
    } catch (e) {
        ctx.body = response(NetCode.ERROR, null,`注册失败：${e.message}`);
    }
}

// 登录
export async function login(ctx){
    const user = ctx.request.body
    try{
        const [userInfo] = await loginUser(user);
        if(userInfo){
            const token = jwt.sign(userInfo, PRIVATE_KEY, {
                expiresIn: 24 * 60 * 60,
                algorithm: 'RS256'
            })
            ctx.body = response(NetCode.SUCCESS, {token}, '登录成功')
        } else {
            ctx.body = response(NetCode.ERROR, null, `登录失败: 用户名或密码错误`)
        }
    } catch (e) {
        ctx.body = response(NetCode.ERROR,null, `登录失败: ${e.message}`)
    }
}
// 登出
export async function logout(ctx){
    ctx.body = response(NetCode.SUCCESS, null, '成功退出登录');
}
